package com.swg.myspring.util;

import com.swg.myspring.bean.BeanDefinition;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.net.URL;
import java.util.*;

public class SwgClassPathXmlApplicationContext {
    private List<BeanDefinition> beanDefines=new ArrayList<BeanDefinition>();//用来存储所有的beans
    private Map<String, Object> sigletons =new HashMap<String, Object>();//用来存储实例化后的bean

    public SwgClassPathXmlApplicationContext(String fileName){
        this.readXml(fileName);
        this.instanceBeans();
    }

    private void readXml(String fileName) {
        SAXReader saxReader=new SAXReader();
        Document document=null;
        try {
            //获取要读取的配置文件的路径
            URL xmlPath=this.getClass().getClassLoader().getResource(fileName);
            //读取文件内容
            document=saxReader.read(xmlPath);
            //获取xml中的根元素
            Element rootElement=document.getRootElement();
            for (Iterator iterator = rootElement.elementIterator(); iterator.hasNext();) {
                Element element = (Element) iterator.next();
                String id=element.attributeValue("id");//获取bean的id属性值
                String clazz=element.attributeValue("class");//获取bean的class属性值
                BeanDefinition beanDefinition=new BeanDefinition(id,clazz);
                beanDefines.add(beanDefinition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void instanceBeans(){
        if(beanDefines!=null && beanDefines.size()>0){
            for(BeanDefinition beanDefinition:beanDefines){
                try {
                    if (beanDefinition.getClassName() != null && !beanDefinition.getClassName().equals("")) {
                        sigletons.put(beanDefinition.getId(),Class.forName(beanDefinition.getClassName()).newInstance());
                        System.out.println("id为："+beanDefinition.getId()+"的bean实例化成功");
                    }
                }catch (Exception e){
                    System.out.println("bean实例化失败");
                    e.printStackTrace();
                }
            }
        }
    }

    public Object getBean(String beanName,Class beanClass){
        return sigletons.get(beanName);
    }



}
